<template>
    <div class="container">
        <div class="login-box">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" :size="formSize">
                <el-form-item prop="username">
                    <el-input v-model="ruleForm.username" size="large" placeholder="请输入用户名" :prefix-icon="User" />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="ruleForm.password" type="password" show-password size="large" placeholder="请输入密码"
                        :prefix-icon="Lock" />
                </el-form-item>
                <el-form-item prop="captcha">
                    <el-input v-model="ruleForm.captcha" style="width: 180px" size="large" placeholder="验证码"
                        :prefix-icon="Grid" />
                    <div class="captcha" @click="handleGetCaptcha">{{ code }}</div>
                </el-form-item>
                <el-form-item justify="end">
                    <el-checkbox v-model="checked" size="large">记住密码</el-checkbox>
                </el-form-item>
                <el-form-item>
                    <el-button class="login-btn" type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts" name="Login">
import { ref, reactive, onMounted } from 'vue';
import type { RuleForm } from './type';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
import { User, Lock, Grid } from '@element-plus/icons-vue';
import { getCaptcha, login } from '@/api/common/system';
import { useCaptchaStore } from '@/stores/modules/captcha';
import { useUserStore } from '@/stores/modules/user';
import cookie from '@/utils/cookie';
import useLogin from '@/hooks/useLogin'
import { navigationTo, Message } from '@/utils/tool';

const code = ref<string>('');
const checked = ref(false);
const formSize = ref<ComponentSize>('default');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
    username: '',
    password: '',
    captcha: ''
});

const checkCaptcha = (rule: any, value: any, callback: any) => {
    if (value != captchaStore.verifyCode)
        callback(new Error('验证码错误'));
    else
        callback();
}

const rules = reactive<FormRules<RuleForm>>({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 40, message: '密码不能少于6位数', trigger: 'blur' },
    ],
    captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { validator: checkCaptcha, trigger: 'blur' }
    ],
});

const captchaStore = useCaptchaStore();

function verify() {
    getCaptcha().then(res => {
        code.value = res.data;
        captchaStore.verifyCode = res.data.toLowerCase();
    }).catch(err => {});
}

function handleGetCaptcha() {
    verify();
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            login(ruleForm).then(res => {
                let loginInfo = {
                    username: ruleForm.username,
                    password: ruleForm.password,
                    autoLogin: true
                };

                if (!checked.value) {
                    loginInfo.username = '';
                    loginInfo.password = '';
                    loginInfo.autoLogin = false;
                }
                cookie.setCookie('LOGIN', loginInfo, 0);

                let user = {
                    id: res.data.userInfo.id,
                    username: res.data.userInfo.username,
                    name: res.data.userInfo.name,
                    token: res.data.token,
                };
                cookie.setCookie('USER', user, 1);

                const userStore = useUserStore();
                userStore.$patch(user);
                Message('登陆成功', 'success');
                navigationTo('/')
            }).catch(err => { })
        } else {
            console.log('error submit!', fields)
        }
    })
}

onMounted(() => {
    let { username, password, autoLogin } = useLogin();
    if (autoLogin.value) {
        ruleForm.username = username.value;
        ruleForm.password = password.value;
        checked.value = autoLogin.value;
    }

    verify();
});

</script>

<style lang="scss" scoped>
.container {
    width: 100%;
    height: 100vh;
    background-image: url('@/assets/bg-images/login-bg1.jpeg');
    background-size: 100% 100%;
    position: relative;

    .login-box {
        width: 360px;
        padding: 50px 30px;
        background-color: #9d9b9b52;
        border-radius: 10px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-180px, -191px);

        .captcha {
            width: 100px;
            height: 40px;
            margin-left: 20px;
            border-radius: 4px;
            background-color: #fff;
            text-align: center;
            line-height: 40px;
            font-size: 16px;
            letter-spacing: 2px;
            color: #696666;
        }

        .login-btn {
            width: 100%;
        }
    }
}
</style>
